/*
 * @Date         : 2024-05-17 11:13:25 星期5
 * @Author       : xut
 * @Description  :
 */
import jwt, { SignOptions } from "jsonwebtoken"
import { envConfig } from "../config/default"

export async function signJwt(
  payload: Object,
  key: "accessTokenPrivateKey" | "refreshTokenPrivateKey",
  options: SignOptions = {}
) {
  const privateKey = Buffer.from(envConfig[key], "base64").toString("ascii")
  return await jwt.sign(payload, privateKey, { ...options, algorithm: "RS256" })
}

export async function verifyJwt<T>(
  token: string,
  key: "accessTokenPublicKey" | "refreshTokenPublicKey"
): Promise<T | null> {
  try {
    const publicKey = Buffer.from(envConfig[key], "base64").toString("ascii")
    return (await jwt.verify(token, publicKey)) as T
  } catch (error) {
    console.log(error)
    return null
  }
}
